package br.ita.comp.ces22.quiz.core.dao.jdbc;


import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import br.ita.comp.ces22.quiz.core.ConnectionManager;
import br.ita.comp.ces22.quiz.core.dao.DAO;
import br.ita.comp.ces22.quiz.domain.Question;

public class QuestionJDBCDAO implements DAO<Question> {

	public Question getById(Object oIdQuestion) {
		PreparedStatement stm = null;
		ResultSet rs = null;
		try {
			Integer idQuestion = (Integer) oIdQuestion;
			String query = "SELECT * FROM question where idquestion= ?";
			stm = ConnectionManager.getInstance().openConnection().prepareStatement(query);
			stm.setInt(1, idQuestion.intValue());
			rs = stm.executeQuery();
			
			if (rs.next()) {
				Question question = new Question();
				question.setQuestion(rs.getString("question"));
				question.setAlternative1(rs.getString("alternative1"));
				question.setAlternative2(rs.getString("alternative2"));
				question.setAlternative3(rs.getString("alternative3"));
				question.setAlternative4(rs.getString("alternative4"));
				question.setAlternative5(rs.getString("alternative5"));
				question.setIdQuestion(new Integer(rs.getInt("idquestion")));
				question.setRightAns(new Integer(rs.getString("rightans")));
				return question;
			}
			return null;

		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				stm.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void insert(Question question) {
		PreparedStatement stm = null;
		try {
			String query = "INSERT INTO question("
				+ "idquestion, question, alternative1, alternative2, alternative3, alternative4, alternative5, rightans)"
				+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
			
			stm = ConnectionManager.getInstance().openConnection().prepareStatement(query);
			
			stm.setInt(1, question.getIdQuestion().intValue());
			stm.setString(2, question.getQuestion());
			stm.setString(3, question.getAlternative1());
			stm.setString(4, question.getAlternative2());
			stm.setString(5, question.getAlternative3());
			stm.setString(6, question.getAlternative4());
			stm.setString(7, question.getAlternative5());
			stm.setInt(8,question.getRightAns().intValue());
			
			stm.execute();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				stm.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}